package com.niit.project.dao.impl;

import com.niit.project.dao.UserDao;
import com.niit.project.entity.Goods;
import com.niit.project.entity.Page;
import com.niit.project.entity.User;
import com.niit.project.utils.Dbutils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

public class UserDaoImpl implements UserDao{
    QueryRunner queryRunner = new QueryRunner();
    @Override
    public List<Goods> selectAll(Page page) {
        try {
            List<Goods> goods = queryRunner.query(Dbutils.getConnection(),"select * from goods ?,?",new BeanListHandler<Goods>(Goods.class),page.getStartRows(),page.getPageSize());
            return goods;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public long selectCount() {
        try {
            long count = (long) queryRunner.query(Dbutils.getConnection(),"select count(*) from goods",new ScalarHandler());
            return count;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public int delete(int id) {
//        int result = queryRunner.update(Dbutils.getConnection(),"de")
        return id;
    }

    @Override
    public int insert(Goods goods) {
        return 0;
    }

    @Override
    public User select(String username) {
        try {
            User user = queryRunner.query(Dbutils.getConnection(),"select * from user where username = ?",new BeanHandler<User>(User.class),username);
            return user;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public int update(Goods goods) {
        return 0;
    }

    @Override
    public int insert(User user) {
        try {
            int result = queryRunner.update(Dbutils.getConnection(),"insert into user (username,password,nickname,contact,gender) values(?,?,?,?,?)",user.getUsername(),user.getPassword(),user.getNickname(),user.getContact(),user.getGender());
            return result;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
